import React, { useEffect, useCallback } from 'react'
import { Empty } from 'antd'
import { useTaskStore } from '@/store'
import TaskNode from './component/TaskNode'
import TaskNodeEdit from './component/TaskNodeEdit'
import { TaskItem } from '@/types'
import { taskItemTypeConfig } from './config'
import TaskActions from './component/TaskActions'

const Tasks = React.memo(function Tasks(): React.JSX.Element {
  const showNewTaskForm = useTaskStore((state) => state.showNewTaskForm)
  const selectedTypes = useTaskStore((state) => state.selectedTypes)

  const { loadTasks, renderTasks, addTask, deleteTask, onShowNewTaskForm } = useTaskStore()
  const { activeTasks, completedTasks } = renderTasks()

  useEffect(() => {
    loadTasks()
  }, [loadTasks])

  // 处理新任务保存
  const handleSaveNewTask = useCallback(
    (task: TaskItem) => {
      addTask(task)
      onShowNewTaskForm(false)
    },
    [addTask, onShowNewTaskForm]
  )

  // 取消新任务创建
  const handleCancelNewTask = useCallback(() => {
    onShowNewTaskForm(false)
  }, [onShowNewTaskForm])

  return (
    <div className="h-full w-full p-4 overflow-y-auto bg-bg2">
      {/* 顶部操作栏 */}
      <TaskActions />

      {/* 新任务表单 */}
      {showNewTaskForm && (
        <TaskNodeEdit onSave={handleSaveNewTask} onCancel={handleCancelNewTask} />
      )}

      {/* 任务列表 - 所有任务放在一起 */}
      {activeTasks.length > 0 || completedTasks.length > 0 ? (
        <>
          {activeTasks.map((task) => (
            <TaskNode key={task.id} task={task} deleteTask={deleteTask} />
          ))}
          {completedTasks.map((task) => (
            <TaskNode key={task.id} task={task} deleteTask={deleteTask} />
          ))}
        </>
      ) : (
        <div className="flex justify-center items-center py-12">
          <Empty
            description={
              selectedTypes.has('all')
                ? '暂无任务'
                : `暂无${Array.from(selectedTypes)
                    .map((type) => (type !== 'all' ? taskItemTypeConfig[type].title : ''))
                    .filter(Boolean)
                    .join('/')}类型的任务`
            }
            className="text-gray-500"
          />
        </div>
      )}
    </div>
  )
})

export default Tasks
